/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"A707E557-89D9-4C08-B0D8-1F12DB4C21DA",variableType:4}
 */
var fDeudaPaga = 0;

/**
 * @type {Number}
 *
 * @properties={typeid:35,uuid:"263D1D65-59AD-427A-90E3-E721B37B1CEA",variableType:4}
 */
var fCentro = null;

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"DAF091C2-59CA-4574-ADB6-E5A1F52FD5AA"}
 */
function buscar(event) {
	var $campo_tb
	if (fDeudaPaga == 0)
	{
		$campo_tb = 'tb.diario_compras'
	}
	else
	{
		$campo_tb = 'tb.diario_pagos'
	}
	var $query = 'select cc.centro_id, p.plancta_id_normal as "cuenta_id", SUM(importe) as "total" FROM ctacte_pr "cc" '+
					' JOIN proveedor "p" ON p.proveedor_id = cc.proveedor_id '+
					' JOIN tab_mov_pr "tb" ON cc.cod_mov = tb.ctacte_mov_pr_id '+
					' WHERE ' + $campo_tb + ' = 1 AND cc.fecha_mov BETWEEN ? and ? '
	/** @type {Array<Object>}*/
	var args = [globals.gFechaDesde, globals.gFechaHasta]
	
	if (fCentro != null)
	{
		$query += ' AND cc.centro_id = ? '
		args.push(fCentro)
	}
	else
	{
		$query += ' AND cc.centro_id is not null '
	}
	$query += ' group by p.plancta_id_normal, cc.centro_id order by cc.centro_id '
	
	var $ds = databaseManager.getDataSetByQuery('infocom',$query,args,-1)
	
	if ($ds.getMaxRowIndex() == 0)
	{
		globals.DIALOGS.showWarningDialog('Aviso','No se encontraron resultados','OK')
		return
	}
	$ds.addColumn('total_centro',4)
	$ds = calcularTotalesCentro($ds)
	var $frm = solutionModel.getForm('rpt_centro_contable_2')
	var $tipos = [JSColumn.INTEGER, JSColumn.INTEGER, JSColumn.NUMBER, JSColumn.NUMBER]
	$frm.dataSource = $ds.createDataSource('RPT_CENTRO_CONTABLE',$tipos)
	forms[$frm.name].controller.recreateUI()
	forms[$frm.name].controller.sort('centro_id asc')
	forms.rpt_centro_contable_2.pdf()
}

/**
 * @param {JSDataSet} ds
 *
 * @properties={typeid:24,uuid:"B331814B-C24C-4168-84FD-3DBF9B2B0683"}
 */
function calcularTotalesCentro(ds)
{
	var $pp = 1
	var $centro = ds.getValue(1,1)
	var $total = 0
	var $totalGral = 0
	for (var i = 1 ; i <= ds.getMaxRowIndex() ; i++)
	{
		if ($centro == ds.getValue(i,1))
		{
			$total += ds.getValue(i,3)
		}
		else
		{
			ds.setValue($pp,4,$total)
			$total = ds.getValue(i,3)
			$centro = ds.getValue(i,1)
			$pp = i
		}
		$totalGral += ds.getValue(i,3)
	}
	ds.setValue($pp,4,$total)
	forms.rpt_centro_contable_2.fTotalGral = $totalGral
	return ds
}
